﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HFCAutoConfig
{
    public partial class Form1 : Form
    {
        SerialPort sp = new SerialPort();
        public delegate void EventHandle(byte[] readBuffer);
        public event EventHandle DataReceived;
        Thread thread;
        volatile bool _keepReading;
        public static Form1 ME { get; set; }

        private byte[] cmdedArray = new byte[64];   //待发送命令

        private int cmdoffset = 0;      //发送字节位

        private bool cmd_ended = true; //是否已完成命令发送
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            thread = null;
            _keepReading = false;
            DataReceived += new EventHandle(DataReceiving);
        }
        public void SerialConnect()
        {
            SerialDisConnect();
            sp.PortName = Properties.Settings.Default.comname;
            sp.BaudRate = Properties.Settings.Default.com_hz;
            sp.DataBits = Properties.Settings.Default.com_d;
            sp.StopBits = StopBits.One;
            sp.Parity = System.IO.Ports.Parity.None;
            sp.ReadTimeout = 100;
            try
            {
                sp.Open();
                if (sp.IsOpen)
                {
                    StartReading();
                }
                else
                {
                    MessageBox.Show("串口打开失败！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            
        }     


        private void DataReceiving(byte[] readBuffer)
        {
            if (readBuffer.Length > 0)
            {
                string readstr = System.Text.Encoding.Default.GetString(readBuffer);

                /*readstr = readstr.Replace("\0", "");
                readstr = readstr.Replace("\n\r", "\r\n");
                txt_console.AppendText(readstr);
                txt_console.ScrollToCaret();*/

                if ((cmdoffset < cmdedArray.Length - 1) && cmd_ended == false)
                {
                    txt_console.AppendText(readstr);
                    //发送下一个字节
                    cmdoffset++;
                    WritePort(cmdedArray,cmdoffset,1);
                }
                else
                {
                    if(cmd_ended == false)
                    {
                        cmd_ended = true;
                        //发送换行符
                        WritePort(System.Text.Encoding.Default.GetBytes("\r"), 0, System.Text.Encoding.Default.GetBytes("\r").Length);
                    }
                    
                    readstr = readstr.Replace("\0", "");
                    readstr = readstr.Replace("\n\r", "\r\n");
                    txt_console.AppendText(readstr);
                    txt_console.ScrollToCaret();
                }

            }
        }
       

        private void WriteCmdTo()
        {
            //发送修改MAC命令
            byte[] cmdArray = new byte[64];
            string cmdstr = "";            
            cmdstr = txt_mm.Text.Trim() + "\r";
            //txt_mac.Text = "";
            cmdArray = System.Text.Encoding.Default.GetBytes(cmdstr);
            WritePort(cmdArray, 0, cmdArray.Length);
            Thread.Sleep(400);

            //设置设备序列号            
            cmdstr = "pcb " + txt_pcb.Text.Trim() + "\r";
            //txt_sn.Text = "";
            cmdArray = new byte[64];
            cmdArray = System.Text.Encoding.Default.GetBytes(cmdstr);
            WritePort(cmdArray, 0, cmdArray.Length);
            Thread.Sleep(400);
             
            //修改设备型号
            cmdstr = "outpower " + txt_outpower.Text.Trim() + "\r";
            //txt_devtype.Text = "";
            cmdArray = new byte[64];
            cmdArray = System.Text.Encoding.Default.GetBytes(cmdstr);
            WritePort(cmdArray, 0, cmdArray.Length);
            Thread.Sleep(400);
                
            

            //设备型号锁定
            cmdstr = "setda 1 " + txt_da1.Text.Trim() + "\r";
            cmdArray = new byte[64];
            cmdArray = System.Text.Encoding.Default.GetBytes(cmdstr);
            WritePort(cmdArray, 0, cmdArray.Length);
            Thread.Sleep(400);

            cmdstr = "setda 2 " + txt_da2.Text.Trim() + "\r";
            cmdArray = new byte[64];
            cmdArray = System.Text.Encoding.Default.GetBytes(cmdstr);
            WritePort(cmdArray, 0, cmdArray.Length);
            Thread.Sleep(400);
            
        }

        private void SerialDisConnect()
        {
            StopReading();
            sp.Close();
        }

        private void StartReading()
        {
            if (!_keepReading)
            {
                _keepReading = true;
                thread = new Thread(new ThreadStart(ReadPort));
                thread.Start();
            }
        }

        private void StopReading()
        {
            if (_keepReading)
            {
                _keepReading = false;
                thread.Join();
                thread = null;
            }
        }

        private void ReadPort()
        {
            while (_keepReading)
            {
                if (sp.IsOpen)
                {                    
                    int count = sp.BytesToRead;
                    if (count > 0)
                    {

                        byte[] readBuffer = new byte[count];                      
                        try
                        {
                            Application.DoEvents();
                            sp.Read(readBuffer, 0, count);
                            if (DataReceived != null)
                                DataReceived(readBuffer);
                            Thread.Sleep(20);
                        }
                        catch (TimeoutException)
                        {
                        }
                    }
                }
                Thread.Sleep(20);
            }
        }

        private void WritePort(byte[] send, int offSet, int count)
        {
            if (sp.IsOpen)
            {
                sp.Write(send, offSet, count);
            }      
            
        }

        private void SendData()
        {
            //firststart = false;
            //validating = false;
            //macstr = txt_pcb.Text;
            //snstr = txt_outpower.Text;
            //typestr = txt_da1.Text;
            //idstr = txt_da2.Text;
            WriteCmdTo();            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //txt_da1.Text = Properties.Settings.Default.com_devtype;
            //txt_da2.Text = Properties.Settings.Default.com_devid;
            ME = this;
            if (Properties.Settings.Default.comname != "")
            {
                SerialConnect();
            }
            this.ActiveControl = txt_mm;
        }

        private void btn_config_Click(object sender, EventArgs e)
        {
            Config cf = new Config();
            cf.ShowDialog();
            txt_pcb.Focus(); 
        }

        private void btn_write_Click(object sender, EventArgs e)
        {
            
            //SendData();           

        }

        

        private void txt_mac_TextChanged(object sender, EventArgs e)
        {
           
        }

        private void txt_sn_TextChanged(object sender, EventArgs e)
        {
            
            
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            SerialDisConnect();
        }

        private void DoSend(string strcmd)
        {
            
            //发送修改MAC命令
            byte[] cmdArray = new byte[strcmd.Length];                 
            cmdArray = System.Text.Encoding.Default.GetBytes(strcmd);
            cmdedArray = new byte[cmdArray.Length];
            Array.Copy(cmdArray, cmdedArray, cmdArray.Length);
            //发送第一个字节
            cmd_ended = false;
            WritePort(cmdArray, 0, 1);
            cmdoffset = 0;
            /*for (int i = 0; i < cmdArray.Length; i++)
            {
                WritePort(cmdArray, i, 1);
                Thread.Sleep(300);
            }*/


            /*cmdArray = new byte[64];
            string cmdstr = "\r";
            cmdArray = System.Text.Encoding.Default.GetBytes(cmdstr);
            WritePort(cmdArray, 0, cmdArray.Length);*/
        }

        private void txt_mm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                DoSend(txt_mm.Text);
            }
        }

        private void txt_pcb_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                DoSend("entplogo -1 " + txt_pcb.Text.Trim());
            }
        }

        private void txt_outpower_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                DoSend("entplogo -2 " + txt_outpower.Text.Trim());
            }
        }

        private void txt_da1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                DoSend("setsn " + txt_da1.Text.Trim());
            }
        }

        private void txt_da2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                DoSend("ethcfg mac " + txt_da2.Text.Trim());
            }
        }

        private void txt_ip_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                DoSend("ethcfg ip " + txt_ip.Text.Trim());
            }
        }

        private void txt_setitu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                DoSend("setitu " + txt_setitu.Text.Trim());
            }
        }
        

    }
}
